package com.example.socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @Date 2022/10/15
 * @Author Jonathan
 */
public class ClientDemo {

    private static final Logger log = LoggerFactory.getLogger(ClientDemo.class);

    private static final String XML_HEADER = "<?xml version=\"1.0\"encoding=\"GBK\"?>";
    private static final String XML_CONTENT = "<hnnx_cydbd><trancode>哈哈哈</trancode><bizToken>425CB547-74F4-4912-BEB2-DE3FFBD74805</bizToken><appid>xxxxxxxxxxxxxxxxxx</appid><ruleid>2</ruleid></hnnx_cydbd>";

    public static void main(String[] args) throws IOException, InterruptedException {
        SocketChannel channel = SocketChannel.open();
        boolean connect = channel.connect(new InetSocketAddress(8000));
        log.info("connect:{}", connect);
        channel.configureBlocking(false);
//        int read = 0;
//        int total = 0;
        String content = XML_HEADER + XML_CONTENT;
        content = String.format("%08d", content.length()) + content;
        byte[] bytes = content.getBytes(Charset.forName("GB2312"));
        ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
        buffer.put(bytes);
        buffer.flip();
        int alreadyWrite = 0;
        do {
            alreadyWrite += channel.write(buffer);
            log.info("alreadyWrite:{}", alreadyWrite);
        } while (alreadyWrite != bytes.length);
        log.info("alreadyWrite:{}", alreadyWrite);
        int headerSize = 8;
        int alreadyReadHeader = 0;
        ByteBuffer headerBuffer = ByteBuffer.allocate(headerSize);
//        SocketChannel channel = (SocketChannel) key.channel();
        do {
            alreadyReadHeader += channel.read(headerBuffer);
        } while (alreadyReadHeader != headerSize);
        log.info("alreadyReadHeader:{}", alreadyReadHeader);
        headerBuffer.flip();
        CharBuffer header = StandardCharsets.UTF_8.decode(headerBuffer);
        headerBuffer.clear();
        int contentLength = Integer.parseInt(header.toString());
        int alreadyReadContent = 0;
        ByteBuffer contentBuffer = ByteBuffer.allocate(contentLength);
        do {
            alreadyReadContent += channel.read(contentBuffer);
        } while (alreadyReadContent != contentLength);
        log.info("alreadyReadContent:{}", alreadyReadContent);
        contentBuffer.flip();
        CharBuffer receivedContent = Charset.forName("GB2312").decode(contentBuffer);
        log.info("receivedContent:{}", receivedContent);
        contentBuffer.clear();
        channel.close();
    }
}
